//
//  HQHListDetailWebViewController.m
//  LastOne
//
//  Created by 小柠檬 on 15/11/5.
//  Copyright © 2015年 sc. All rights reserved.
//

#import "HQHListDetailWebViewController.h"
#import "HTTPMethod.h"
#import "ChangeString.h"
#import "FitHeader.h"
#import "UMSocial.h"
#import "CoreDataManager.h"
#import "HQHReadSave.h"
#import "GiFHUD.h"
@interface HQHListDetailWebViewController ()<UIWebViewDelegate, UMSocialUIDelegate>
@property(nonatomic, strong)UIWebView *webView;
@property(nonatomic, strong)CoreDataManager *manager;
@property(nonatomic, strong)UIBarButtonItem *hotButton;
@property(nonatomic, assign)NSInteger flag;
@property(nonatomic, strong)UIAlertController *alertController;
@property(nonatomic, strong)HQHReadSave *readSave;
@property(nonatomic, strong)NSArray *allList;

@end

@implementation HQHListDetailWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self getData];
    _manager = [CoreDataManager shareManager];
   
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIBarButtonItem *newButton = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"iconfont-iconshujuneibufenxiang"] style:UIBarButtonItemStylePlain target:self action:@selector(shareAction)];
    
    _hotButton = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"iconfont-shoucangweishoucang"] style:UIBarButtonItemStylePlain target:self action:@selector(saveAction)];
    
    NSArray *array = [NSArray arrayWithObjects:_hotButton, newButton, nil];
    self.navigationItem.rightBarButtonItems = array;
    
    _webView = [[UIWebView alloc]init];
    _webView.frame = CGRectMake(0, 0, self.view.frame.size.width, (554 + 49) * FitHeight);
    _webView.delegate = self;
    
    [self.view addSubview:_webView];
    
    [GiFHUD setGifWithImageName:@"loading.gif"];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    
    self.tabBarController.tabBar.hidden = YES;
    
    _flag = 0;
    
    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"HQHReadSave"];
    //[fetchRequest setSortDescriptors:@[sortDescriptor]];
    
    //判段是否收藏
    _allList = [_manager.managedObjectContext executeFetchRequest:fetchRequest error:nil];
    
    for (HQHReadSave *readSave in _allList) {
        //NSLog(@"%@", _readSave);
        if ([readSave.title isEqualToString:_model.title]) {
            NSLog(@"123");
            [_hotButton setImage:[UIImage imageNamed:@"shixin"]];
            _flag = 1;
            break;
        }
    }
    
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    self.tabBarController.tabBar.hidden = NO;
    [GiFHUD dismiss];
}


-(void)getData
{ //NSLog(@"11111%@", [_manager applicationDocumentsDirectory]);
    [GiFHUD show];
    [HTTPMethod getDataByString:@"http://api2.pianke.me/article/info" BodyDic:[ChangeString changeStringToDictionary:[NSString stringWithFormat:@"auth=&client=1&contentid=%@&deviceid=137794B8-2578-4119-B189-3E532E7C0F5B&version=3.0.6", _model.iD]] WithDataBlock:^(id data) {
        NSDictionary *dataDic = [data objectForKey:@"data"];
        [_webView loadHTMLString:[dataDic objectForKey:@"html"] baseURL:nil];
        NSDictionary *shareinfoDic = [dataDic objectForKey:@"shareinfo"];
        self.title = [shareinfoDic objectForKey:@"title"];
    }];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [GiFHUD dismiss];
    NSString *script = [NSString stringWithFormat:@"var script = document.createElement('script');"
                        "script.type = 'text/javascript';"
                        "script.text = \"function ResizeImages() { "
                        "var myimg;"
                        "var maxwidth = %f;"//屏幕宽度
                        "for (i = 0; i < document.images.length; i++) {"
                        "myimg = document.images[i];"
                        "myimg.height = maxwidth / (myimg.width / myimg.height);"
                        "myimg.width = maxwidth;"
                        "}"
                        "}\";"
                        "document.getElementsByTagName('p')[0].appendChild(script);", [UIScreen mainScreen].bounds.size.width - 15 * FitWidth];
    //添加JS
    [webView stringByEvaluatingJavaScriptFromString:script];
    //添加调用JS执行的语句
    [webView stringByEvaluatingJavaScriptFromString:@"ResizeImages();"];
    
        if ([[NSUserDefaults standardUserDefaults] boolForKey:@"night"]) {
            [_webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.background='#2E2E2E'"];
            [_webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextFillColor= 'white'"];
        }
        else{
            [_webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.background='#FFFFFF'"];
            [_webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextFillColor= 'black'"];
        }
    
    

}

-(void)shareAction
{
    NSArray *array = @[UMShareToSina];
    [UMSocialSnsService presentSnsIconSheetView:self appKey:@"56266a4667e58ebce40037de" shareText:nil shareImage:nil shareToSnsNames:array delegate:self];
}

-(void)saveAction
{
  
  
    if (_flag == 0) {
        
        _readSave = [NSEntityDescription insertNewObjectForEntityForName:@"HQHReadSave" inManagedObjectContext:_manager.managedObjectContext];
        _readSave.title = _model.title;
        _readSave.name = _model.name;
        _readSave.coverimg = _model.coverimg;
        _readSave.content = _model.content;
        _readSave.iD = _model.iD;
 
        [_manager saveContext];
        self.alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"收藏成功" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
        [_alertController addAction:action1];
        [_hotButton setImage:[UIImage imageNamed:@"shixin"]];
        _flag = 1;
    }
    else{
        NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"HQHReadSave"];
        for (_readSave in [_manager.managedObjectContext executeFetchRequest:fetchRequest error:nil]) {
            if ([_readSave.title isEqualToString:_model.title]) {
                [_manager.managedObjectContext deleteObject:_readSave];
                NSLog(@"shanbchu");
                [_hotButton setImage:[UIImage imageNamed:@"iconfont-shoucangweishoucang"]];
                _hotButton.tintColor = [UIColor colorWithRed:0 green:0.5 blue:1 alpha:1];
                self.alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"取消收藏" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
                [_alertController addAction:action2];
               // [_manager saveContext];//不能加
                NSLog(@"BBBb%@", _model.title);
                _flag = 0;
                break;
            }
        }
    }
    [self presentViewController:_alertController animated:YES completion:nil];
}

-(void)setModel:(HQHListDetailModel *)model
{
    _model = model;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
